<?php
 /**
  * 导入历史请假记录
  * **/
apf_require_class('Oa_Job_Attendance_Abstract');
class Oa_Job_Attendance_OaSynergyData extends Oa_Job_Attendance_Abstract {

    /** 数据库读 **/
    private $readdb = 'attendance_slave';

    /** 数据库写 **/
    private $writedb = 'attendance_master';

    /** 金蝶数据库读 **/
    private $kdreaddb = 'kd_slave';

    /** 新添加的默认员工角色=>普通员工 请参照表admin_role设置**/
    private $default_user_role = 5;

    /** 需要做排查的部门列表 **/
    private $department_bad_file = "/data1/department_bad_file.csv";

    /**
     * 用户信息,id code superior_code
     */
    private $user_ids;

    private static $dismission;

    public function run() {
        ini_set("memory_limit",'512M');
        $start = microtime(true);
        $this->log("开始执行啦！");
        $this->db_connect();
       //同步部门信息
        $this->syn_department_data();
       //同步人员信息
        $this->syn_userinfo_data();
       //同步部门负责人信息
        $this->syn_department_principal_data();
       //同步组织架构关系
        $this->syn_org_relation();
        //导出没有上级的用户
        //$this->import_superior_null_info();
        $this->log ( "开始同步上下级关系..." );
        $this->get_all_ids();
        $this->clear_db('org_relation');
        //$this->alter_db('org_relation');
        //var_dump($user_ids,count($user_ids));
        foreach($this->user_ids as $key=>$user){
            $this->map_relation($key, $key,$user['superior_code']);
        }
        $this->log ( "结束同步上下级关系..." );
        //导出金蝶里面坏的部门数据
        //$this->import_bad_department_info();
        $end = microtime(true) - $start;
        $this->log("共耗时:".$end);
        $this->log("job执行结束！");
    }

    //同步部门数据
    public function syn_department_data() {
        //排查数据
        //$department_bad_ids = $this->get_department_bad_ids();
        //添加statusID  如果 为 2对该部门做删除处理 is_del = 1
        $s_sql = "select ID,Name,CompanyID,statusID from ORG_Unit,ORG_Department where ID = UnitID";
        $result = mssql_query($s_sql);
        $data = array();
        $kd_department_ids = array();//将金蝶的id放到ids数组里
        $kd_company_ids = array();//金蝶的公司名id,供同步公司名使用
        while( $row = mssql_fetch_assoc($result) ) {
            $rs = array();
            $rs['kd_name'] = $this->set_utf8($row['Name']);
            $rs['kd_id'] = mssql_guid_string($row['ID']);
            $rs['status'] = $row['statusID'];
            /*if(!empty($department_bad_ids[$rs['kd_id']])) {
                continue;
            }*/
            $rs['company_id'] = mssql_guid_string($row['CompanyID']);
            $kd_company_ids[] = mssql_guid_string($row['CompanyID']);
            $kd_department_ids[] = $rs['kd_id'];
            $data[$rs['kd_id']] = $rs;
            unset($row);
        }

        //查询线下已有的部门列表，全部取出，然后做后续的操作
        $s_sql = "select * from department";
        $oa_department = $this->get_db_rows_assoc($s_sql, $this->readdb);

        $oa_department_ids = array();//供最后面的同步部门负责人用

        //用kd_department_id做两边的数据比较,线下有kd_department_id的就update此条数据;
        foreach($oa_department as $oa_id => $v) {
            $kd_department_id = $v['kd_department_id'];
            if(empty($kd_department_id)) {
                continue;
            }
            $oa_department_ids[$oa_id] = $kd_department_id;
            if(isset($data[$kd_department_id])) {
                //更新部门表
                $is_del = 0;
                if($data[$kd_department_id]['status'] == 2) {
                    $is_del = 1;
                }
                $u_sql = "update department set is_del = {$is_del},department_name = '{$data[$kd_department_id]['kd_name']}',kd_company_id = '{$data[$kd_department_id]['company_id']}'
                where kd_department_id = '{$kd_department_id}'";
                $this->execute($u_sql,array(),$this->writedb);
                //更新用户表的冗佘部门数据
                $u_sql = "update user_info set department_name = '{$data[$kd_department_id]['kd_name']}'
                where department_id = '{$v['department_id']}'";
                $this->execute($u_sql,array(),$this->writedb);
                //从金谍的数组中删除，可得到线下没有的部门数据,供下一步使用
                unset($data[$kd_department_id]);
                //将已处理的数据从线下数组中删除.余下的数据是要被删除的
                unset($oa_department[$oa_id]);
            }
        }

        #对线下没有的部门数据做添加操作；
        //1.线下如果有这个部门的名字,且有kd_company_id对应，只是没有对应上金蝶的部门id，对这种数据做线下的金蝶id补全,这样可以保证在不用对用户表里已存在的部门ID做更改。
        foreach($data as $key => $v) {
            foreach($oa_department as $oa_id => $vv) {
                if($v['kd_name'] == $vv['department_name'] && $v['company_id']==$vv['kd_company_id']) {
                    $oa_department_id = $vv['department_id'];
                    $u_sql = "update department set kd_department_id = '{$v['kd_department_id']}' where department_id = $oa_department_id";
                    $this->execute($u_sql,array(),$this->writedb);
                    //将已在线下补上金谍部门id的数据从金蝶数组中删除,供下一步{2中}添加部门使用
                    unset($data[$key]);
                    //将已处理的数据从线下数组中再一次剔除.余下的数据是要被删除的
                    unset($oa_department[$oa_id]);
                }
            }
        }
        //2.排除完1后，余下的就做添加操作
        if(!empty($data)) {
            $in_list = array();
            foreach($data as $v) {
                $is_del = 0;
                if($v['status'] == 2) {
                    $is_del = 1;
                }
                $in_str = "('{$v['kd_name']}','{$v['kd_id']}','{$v['company_id']}',{$is_del})";
                $in_list[] = $in_str;
            }
            $in_list = implode(',',$in_list);
            $in_sql = "insert into department(department_name,kd_department_id,kd_company_id,is_del) values $in_list";
            $this->execute($in_sql,array(),$this->writedb);
        }
        //对没有的数据做删除操作<保留>
         $del_department_ids = array();
         foreach($oa_department as $oa_id => $v) {
             $del_department_ids[] = $oa_id;
         }
         /*if(!empty($del_department_ids)) { //by coldarmy 不对部门作任何删除
             $in_list = implode(',',$del_department_ids);
             $d_sql = "delete from department where department_id in($in_list)";
             $this->execute($d_sql,array(),$this->writedb);
         }*/

        //同步部门表的公司名
        if(!empty($kd_company_ids)) {
            $kd_company_ids = array_unique($kd_company_ids);
            $in_list = implode("','",$kd_company_ids);
            $in_list = "'".$in_list."'";
            $s_sql = "select ID,Name from ORG_Unit where ID in($in_list)";
            $result = mssql_query($s_sql);
            $rs = array();
            while( $row = mssql_fetch_assoc($result) ) {
                $kd_company_id = mssql_guid_string($row['ID']);
                $city_name = $this->set_utf8($row['Name']);
                $u_sql = "update department set city_name='{$city_name}' where kd_company_id='{$kd_company_id}'";
                $this->execute($u_sql,array(),$this->writedb);
            }
        }
        unset($in_list);
        unset($data);
        unset($oa_department);
        unset($del_department_ids);
    }

    /*同步负责人信息*/
    public function syn_department_principal_data() {
        #同步部门负责人
        //0.获得已有部门的map信息
        //1.得到部门的id=>KD_id信息
        //2.用UnitId和IsPrincipal=1查表ORG_Position得到负责人的职位ID
        //3.通过职位ID查到职位ID对应的人EM_ID
        //4.通过EM_ID查线下的数据，得到user_id
        //5.写入表

        #0
        $this->log("开始部门负责人数据同步......");
        $s_sql = "select department_id from department_manager_map";
        $oa_department_map = $this->get_db_rows_assoc($s_sql, $this->readdb);
        $oa_department_map_ids = array();//供最后面的同步部门负责人用
        foreach((array)$oa_department_map as $v) {
            $oa_department_map_ids[] = $v['department_id'];
        }

        #1
        $s_sql = "select department_id,kd_department_id from department where is_del = 0";
        $oa_department = $this->get_db_rows_assoc($s_sql, $this->readdb);
        $oa_department_ids = array();//供最后面的同步部门负责人用

        $kdi = array();//所有金蝶部门IDs
        foreach($oa_department as $oa_id => $v) {
            if(empty($v['kd_department_id'])) {
                continue;
            }
            $oa_department_ids[$v['kd_department_id']] = $oa_id;
            $kdi[] = "'".$v['kd_department_id']."'";
        }
        $kdi = implode(',', $kdi);
        $fetch_all = "select hvre.EM_ID as em_id, op.UnitID as kd from HR_v_Report_EmployeeAllDetailInfo hvre
                    LEFT JOIN  ORG_Position op ON op.ID = hvre.positionID where op.UnitID in ({$kdi}) and op.IsPrincipal=1";
        $result = mssql_query($fetch_all);
        $have_delete = array();
        while( $row = mssql_fetch_assoc($result) ) {
            if(mssql_guid_string($row['em_id'])) {
                $emid = mssql_guid_string($row['em_id']);
                $kd = mssql_guid_string($row['kd']);
                $dep_id = $oa_department_ids[$kd];
                $this->log("部门ID".$dep_id);
                $s_sql = "select user_id from user_info where kd_em_id = '{$emid}' and dimission_date='0000-00-00 00:00:00'";
                $rs = $this->get_db_row($s_sql, $this->readdb);
                if(empty($rs['user_id']) || empty($dep_id)) {
                    $this->log($dep_id."没有负责人数据，请核查！对应的金蝶部门id为：".$kd);
                    continue;
                }
                if(!in_array($dep_id, $have_delete)) {//每个部门负责人清空只做一次
                    $d_sql = "delete from department_manager_map where department_id = $dep_id";
                    $this->execute($d_sql,array(),$this->writedb);
                    $have_delete[] = $dep_id;
                }
                $i_sql = "insert into department_manager_map (department_id,user_id) value($dep_id,{$rs['user_id']})";
                $this->execute($i_sql,array(),$this->writedb);
                unset($oa_department_ids[$kd]);
            }
         }
        /*$department_relation = array();//已创建好对应关系的部门
        foreach((array)$oa_department_ids as $dep_id=>$kd_dep_id) {
            #2
            $s_sql = "select ID from ORG_Position where UnitID = '{$kd_dep_id}' and IsPrincipal=1";
            $result = mssql_query($s_sql);
            $rs = array();
            while( $row = mssql_fetch_assoc($result) ) {
                $rs[] = mssql_guid_string($row['ID']);
            }
            $in_list = implode("','",$rs);
            $in_list = "'".$in_list."'";
            #3
            $s_sql = "select EM_ID from HR_v_Report_EmployeeAllDetailInfo where positionID in($in_list)";
            $result = mssql_query($s_sql);
            $rs = array();
            while( $row = mssql_fetch_assoc($result) ) {
                $rs[] = mssql_guid_string($row['EM_ID']);
            }
            $in_list = implode("','",$rs);
            $in_list = "'".$in_list."'";
            #4
            $s_sql = "select user_id from user_info where kd_em_id in ($in_list) and dimission_date='0000-00-00 00:00:00'";
            $rs = $this->get_db_rows($s_sql, $this->readdb);
            if(empty($rs)) {
                $this->log($dep_id."没有负责人数据，请核查！对应的金蝶部门id为：".$kd_dep_id);
                continue;
            }
            //同步数据
            //1.删除数据
            $d_sql = "delete from department_manager_map where department_id = $dep_id";
            $this->execute($d_sql,array(),$this->writedb);
            foreach($rs as $v) {
                //2.添加数据
                $i_sql = "insert into department_manager_map (department_id,user_id) value($dep_id,{$v['user_id']})";
                $this->execute($i_sql,array(),$this->writedb);
            }

            $department_relation[] = $dep_id;//记录数线下部门的负责人已设置的数据，这些数据之外的部门都要删除对应的map
        }

        /*foreach((array)$oa_department_map_ids as $d_id => $v) {
            if(!in_array($d_id,$department_relation)) {
                $this->log('删除部门'.$d_id."的map信息！");
                $d_sql = "delete from department_manager_map where department_id = $d_id";
                $this->execute($d_sql,array(),$this->writedb);
            }
        }*/
        if(!empty($oa_department_map_ids) && !empty($department_relation)) {
            $wait_del = array_diff($oa_department_map_ids, $department_relation);
            if(count($wait_del) > 0) {
                $wait_del = implode(',', $wait_del);
                $d_sql = "delete from department_manager_map where department_id in  ($wait_del)";
                $this->execute($d_sql,array(),$this->writedb);
                $this->log("清空部门负责人信息:".$wait_del);
            }
        }
        unset($oa_department_map);
        unset($oa_department_map_ids);
        unset($oa_department);

        $this->log("完成组织负责人数据同步！");
        return true;
    }

    //同步人员信息
    public function syn_userinfo_data() {
        //获得线下人员信息，供与金蝶数据对比使用.
        $s_sql = "select user_id,kd_em_id from user_info";
        $oa_userinfo_data = $this->get_db_rows_assoc($s_sql, $this->readdb);

        //得到金蝶部门对线下id的关系
        $kd_department_ids = $this->get_kd_department_ids();
        $s_sql = "select
                  empl.EM_ID,empl.Name,empl.Code,empla.HRMS_UserField_1,empl.EMail,empl.Sex,empl.Telphone,empl.Mobile,empla.FEnglishName,
                  hminfo.EnterGroupDate,hminfo.InDueDate,empl.DimissionTime,empl.Status as onornot,
                  empo.PositionName,empo.JobName,empo.UnitID,empo.UnitName,empo.BusinessGroupName,empo.CompanyName,empo.ServicePeriod,empo.EmployeeType,emdi.Status
                  from HM_Employees as empl
                  left join HM_EmployeesAddInfo as empla on empl.EM_ID=empla.EM_ID
                  left join HM_Em_WorkInfo as hminfo
                  on empl.EM_ID = hminfo.EM_ID
                  left join v_Report_Workinfo as empo
                  on empl.EM_ID = empo.EM_ID
                  left join v_Report_EmployeeDetailInfo as emdi
                  on empl.EM_ID = emdi.EM_ID";
        $result = mssql_query($s_sql);
        $data = array();
        //数据还需要：1.上级工号 superior_code ［在上下级关系里面更新］
        while( $row = mssql_fetch_assoc($result) ) {
            $rs = array();
            $rs['kd_em_id'] = mssql_guid_string($row['EM_ID']);
            $rs['name']     = $this->set_utf8($row['Name']);
            $rs['code']     = $row['Code'];
            $rs['email']    = $row['EMail'];
            $rs['english_name'] = $row['FEnglishName'];
            $rs['sex']      = $row['Sex'];
            #$rs['telphone'] = $row['Telphone'];
            $rs['telphone'] = $row['HRMS_UserField_1'];//电话及分机号
            $rs['mobile']   = $row['Mobile'];
            $rs['enter_date'] = $row['EnterGroupDate'];
            $rs['indue_date'] = $row['InDueDate'];
            $rs['dimission_date'] = $row['onornot'] == 2 ? $row['DimissionTime']:'0000-00-00 00:00:00';
            $rs['position_name']  = $this->set_utf8($row['PositionName']);
            $rs['job_name']       = $this->set_utf8($row['JobName']);
            $rs['department_id'] = mssql_guid_string($row['UnitID']);
            $rs['department_name'] = $this->set_utf8($row['UnitName']);
            $rs['group_name']       = $this->set_utf8($row['BusinessGroupName']);
            $rs['sub_company_name'] = $this->set_utf8($row['CompanyName']);
            $rs['city_name'] = $this->set_utf8($row['CompanyName']);
            $rs['service_period'] = $row['ServicePeriod'];
            $rs['employees_type'] = $this->set_utf8($row['EmployeeType']);
            $rs['job_status'] = $this->set_utf8($row['Status']);
            $data[$rs['kd_em_id']] = $rs;
        }

        $role_user_ids = array();//记录修改用户的user_id,以同步用户角色表user_role

        //用kd_em_id做两边数据比较，如果线下存在这个id,则更新该用户的信息。
        foreach($oa_userinfo_data as $oa_id=>$v) {
            if(!empty($oa_id)) {
                $role_user_ids[] = $oa_id;
            }
            $kd_em_id = $v['kd_em_id'];
            if(empty($kd_em_id)) {
                continue;
            }

            if(isset($data[$kd_em_id])) {
                $_rs = $data[$kd_em_id];
                if(!empty($_rs['indue_date'])){
                    $_rs['indue_date'] = date('Y-m-d H:i:s',strtotime($_rs['indue_date']));
                }
                if(!empty($_rs['enter_date'])){
                    $_rs['enter_date'] = date('Y-m-d H:i:s',strtotime($_rs['enter_date']));
                }
                if(!empty($_rs['dimission_date'])){
                    $_rs['dimission_date'] = date('Y-m-d H:i:s',strtotime($_rs['dimission_date']));
                }

                $u_sql = "update user_info set
                            name='{$_rs['name']}',
                            code='{$_rs['code']}',
                            email='{$_rs['email']}',
                            english_name='{$_rs['english_name']}',
                            sex = '{$_rs['sex']}',
                            telphone = '{$_rs['telphone']}',
                            mobile = '{$_rs['mobile']}',
                            enter_date = '{$_rs['enter_date']}',
                            indue_date = '{$_rs['indue_date']}',
                            dimission_date = '{$_rs['dimission_date']}',
                            position_name = '{$_rs['position_name']}',
                            job_name = '{$_rs['job_name']}',
                            department_id = '{$kd_department_ids[$_rs['department_id']]}',
                            department_name = '{$_rs['department_name']}',
                            group_name = '{$_rs['group_name']}',
                            sub_company_name = '{$_rs['sub_company_name']}',
                            city_name = '{$_rs['city_name']}',
                            service_period = '{$_rs['service_period']}',
                            employees_type = '{$_rs['employees_type']}',
                            job_status = '{$_rs['job_status']}'
                          where kd_em_id = '{$kd_em_id}'";
                $this->execute($u_sql,array(),$this->writedb);
                //从金谍的数组中删除，可得到线下没有的人员数据,供下一步添加人员使用
                unset($data[$kd_em_id]);
                //将已处理的数据从线下数组中删除.余下的数据是要被删除的[不做删除操作]
                unset($oa_userinfo_data[$oa_id]);
            }
        }

        //添加没有的数据
        if(!empty($data)) {
            foreach($data as $v) {

                if(!empty($v['indue_date'])){
                    $v['indue_date'] = date('Y-m-d H:i:s',strtotime($v['indue_date']));
                }
                if(!empty($v['enter_date'])){
                    $v['enter_date'] = date('Y-m-d H:i:s',strtotime($v['enter_date']));
                }
                if(!empty($v['dimission_date'])){
                    $v['dimission_date'] = date('Y-m-d H:i:s',strtotime($v['dimission_date']));
                }

                $in_str = "('{$v['name']}','{$v['code']}','{$v['kd_em_id']}','{$v['email']}','{$v['english_name']}'
                           ,'{$v['sex']}','{$v['telphone']}','{$v['mobile']}','{$v['enter_date']}','{$v['indue_date']}'
                           ,'{$v['dimission_date']}','{$v['position_name']}','{$v['job_name']}','{$v['department_id']}','{$v['department_name']}','{$v['group_name']}'
                           ,'{$v['sub_company_name']}','{$v['city_name']}','{$v['service_period']}','{$v['employees_type']}','{$v['job_status']}')";
                $i_sql = "insert into user_info (name,code,kd_em_id,email,english_name,
                sex,telphone,mobile,enter_date,indue_date,
                dimission_date,position_name,job_name,department_id,department_name,group_name,
                sub_company_name,city_name,service_period,employees_type,job_status) value $in_str";
                $uid = $this->execute($i_sql,array(),$this->writedb);

                //新添加的员工默认为普通员工,即admin_role表中的普通员工角色id => 5
                $uid = (int)$uid;
                if($uid>0) {
                    $i_sql = "insert into user_role (user_id,role_id) value ($uid,$this->default_user_role)";
                    $this->execute($i_sql,array(),$this->writedb);
                }
            }
        }

        //核查老用户角色信息,对在角色表里没有的用户做 “普通员工” 角色处理
        $role_user_ids = array_chunk($role_user_ids,100);
        foreach($role_user_ids as $v) {
            $in_list = implode(',',$v);
            $s_sql = "select * from user_role where user_id in ($in_list)";
            $rs = $this->get_db_rows_assoc($s_sql, $this->readdb);
            if(!empty($rs)) {
                foreach($v as $key=>$_uid) {
                    if(isset($rs[$_uid])) {
                        unset($v[$key]);
                    }
                }
           }
           if(!empty($v)) {
                foreach($v as $_uid) {
                    //老用户没有角色，做添加 “普通员工”操作
                    $i_sql = "insert into user_role (user_id,role_id) value ($_uid,$this->default_user_role)";
                    $this->execute($i_sql,array(),$this->writedb);
                }
           }
        }

        //员工离职后，员工的部门信息在金蝶里面会被移到表V_Report_DimissionUnionFireInfo里面，需要单独对部门信息做处理
        $this->log('开始对离职员工的信息做update');
        $s_sql = "select EM_ID,UnitID,UnitName,CompanyName
                     from
                     HR_v_Report_EmployeeAllDetailInfo
                     where
                     dimissiontime > 0";

        $result = mssql_query($s_sql);
        while( $row = mssql_fetch_assoc($result) ) {
            $e_id = mssql_guid_string($row['EM_ID']);
            $d_id = $kd_department_ids[mssql_guid_string($row['UnitID'])];
            $d_id = empty($d_id) ? 0:$d_id;
            $u_sql = "update user_info set department_id = {$d_id},department_name = '{$this->set_utf8($row['UnitName'])}',city_name = '{$this->set_utf8($row['CompanyName'])}' where kd_em_id = '{$e_id}'";
            $this->execute($u_sql,array(),$this->writedb);
        }

        //将金蝶里没有的用户<用户表，角色表>，做离职处理 close by coldarmy 20121017
        /*if(!empty($oa_userinfo_data)) {
            //离职时间取公司创建之前的时间，以便区分
            foreach($oa_userinfo_data as $v) {
                $u_sql = "update user_info set dimission_date = '2006-01-01 00:00:00',job_status='离职' where kd_em_id='{$v['kd_em_id']}'";
                $this->execute($u_sql,array(),$this->writedb);
            }
        }*/
        return true;
    }

    private $user_lelation_level = array();//上下级层级对应关系 array('$uid_$suid'=>$level)

    //同步组织结构关系
    public function syn_org_relation() {
        //获得线下人员信息，供与金蝶数据对比使用.
        $s_sql = "select user_id,name,code,superior_code,dimission_date from user_info where dimission_date = '0000-00-00 00:00:00' order by user_id asc";
        $oa_userinfo_data = $this->get_db_rows_assoc($s_sql, $this->readdb);

        //组合code=>user_id关系，供后面通过code去获取user_id用
        $oa_userinfo_code_ids = array();
        $allcode = array();
        foreach($oa_userinfo_data as $v) {
            $oa_userinfo_code_ids[$v['code']] = array($v['user_id'],$v['superior_code']);
            $allcode[] = "'".$v['code']."'";
        }
        $start = microtime();
        $allcode = implode(',', $allcode);
        $parent_select = "select hvre.Name,hvre.Code as pcode,he.Code as code,hvre.Status as pStatus FROM HR_v_Report_EmployeeAllDetailInfo hvre
                 LEFT JOIN ORG_Position op ON op.ParentID = hvre.PositionID
                 LEFT JOIN  v_Report_Workinfo vrw  ON op.ID = vrw.PositionID
                 LEFT JOIN HM_Employees he ON he.EM_ID = vrw.EM_ID WHERE he.Code in ({$allcode}) AND he.Status = 1";// AND he.DimissionTime is null AND hvre.DimissionTime is null
        $Parent_act = mssql_query($parent_select);
        $num = 0;
         while($row = mssql_fetch_assoc($Parent_act)) {
             $pstatus = $this->set_utf8($row['pStatus']);
             if($pstatus == '在职' && $row['pcode'] != $oa_userinfo_code_ids[$row['code']][1]) {
                $u_sql = "update user_info set superior_code = '{$row['pcode']}' where user_id = {$oa_userinfo_code_ids[$row['code']][0]}";
                $this->execute($u_sql,array(),$this->writedb);
             }
             $num++;
         }
         $this->log($num);
         $cut = microtime() - $start;
         $this->log("耗时".$cut);

         /*

         $user_relation = array();//员工的下上级关系
         $job_status_del = array();//对已离职的员工，删除上下级关系。
         $num = 0;
         foreach($oa_userinfo_data as $user_id=>$v) {
             if($v['job_status']=='离职' || $v['dimission_date']!='0000-00-00 00:00:00') {
                $d_sql = "delete from org_relation where user_id = {$user_id} OR superior_id = {$user_id}";
                $this->execute($d_sql,array(),$this->writedb);
                //$d_sql = "delete from org_relation where superior_id = {$user_id}";
                //$this->execute($d_sql,array(),$this->writedb);
                $this->log('员工'.$v['name'].'已离职！');
                $oa_userinfo_data[$user_id] = array();unset($oa_userinfo_data[$user_id]);
                continue;
             }
             $this->log("开始处理".$v['name']."员工ID:".$user_id."数据");
             $code = $v['code'];
             /*$Parent_select = "select Name,EM_ID,Code from HR_v_Report_EmployeeAllDetailInfo where PositionID in
             (select ParentID from ORG_Position where ID in
             (select PositionID from  v_Report_Workinfo where EM_ID in
             (select EM_ID from HM_Employees where (DimissionTime is null) and Code = '$code'))) and DimissionTime is null";
             $parent_select = "select hvre.Name,hvre.EM_ID,hvre.Code,he.Code FROM HR_v_Report_EmployeeAllDetailInfo hvre
                 LEFT JOIN ORG_Position op ON op.ParentID = hvre.PositionID
                 LEFT JOIN  v_Report_Workinfo vrw  ON op.ID = vrw.PositionID
                 LEFT JOIN HM_Employees he ON he.EM_ID = vrw.EM_ID WHERE he.DimissionTime is null AND he.Code in () AND hvre.DimissionTime is null";
             $Parent_act = mssql_query($Parent_select);
             $Parent_result = mssql_fetch_assoc($Parent_act);

             $Parent_Code = $Parent_result['Code'];
             //同步user_info中的员工上司code
             if(!empty($Parent_Code)) {
                 if($Parent_Code != $v['superior_code']) {
                     $u_sql = "update user_info set superior_code = '{$Parent_Code}' where user_id = {$user_id}";
                     $this->execute($u_sql,array(),$this->writedb);
                 }

                 #获得上司的user_id,以同步表org_relation
                 //$Parent_user_id = $oa_userinfo_code_ids[$Parent_Code];
                 $user_relation[$user_id] = $oa_userinfo_code_ids[$Parent_Code];

             }else {
                 $user_relation[$user_id] = 0;
             }
             $oa_userinfo_data[$user_id] = array();unset($oa_userinfo_data[$user_id]);
         }


/*测试数据*/
//         $user_relation['5'] = 0;
//         $user_relation['1'] = 3;
//         $user_relation['2'] = 3;
//         $user_relation['3'] = 4;
//         $user_relation['4'] = 5;
/*测试数据*/
        /*foreach($user_relation as $user_id=>$pid) {
            if(empty($pid)) {
                $this->user_lelation_level[$user_id.'_'.$pid] = 0;
                continue;
            }
            $this->get_relation_level($user_id,$pid,$user_relation);
        }

        if(!empty($this->user_lelation_level)) {

            $nowid = 0;
            while(true) {
                $un_user_lelation = array();//要删除的上下级关系
                $s_sql = "select * from org_relation where id > $nowid order by id asc limit 100";
                $rs = $this->get_db_rows($s_sql, $this->readdb);
                if(empty($rs)) {
                    break;
                }
                foreach($rs as $v) {
                    $nowid = $v['id'];
                    $user_lelation = $v['user_id'].'_'.$v['superior_id'];
                    if(isset($this->user_lelation_level[$user_lelation])) {
                        if($this->user_lelation_level[$user_lelation]!=$v['level']){
                            $u_sql = "update org_relation set level = ".$this->user_lelation_level[$user_lelation]." where user_id = ".$v['user_id']." and superior_id = ".$v['superior_id']."";
                        }
                        //删除已验证并已处理的层级对应关系,佘下的便是要建立的上下级对应关系。
                        unset($this->user_lelation_level[$user_lelation]);
                    }else{
                        //得到在线下存在，而在金蝶中不存在的上下级对应关系。表示此人的上下级关系已不在，这批数据要删除！
                        $un_user_lelation[] = $v['id'];
                    }
                }

                if(!empty($un_user_lelation)) {
                    $del_ids = implode(',',$un_user_lelation);
                    $d_sql = "delete from org_relation where id in($del_ids)";
                    $this->execute($d_sql,array(),$this->writedb);
                }
            }

            foreach((array)$this->user_lelation_level as $user_list => $level) {
                $in_list = explode('_',$user_list);
                $u_id = $in_list['0'];
                $s_id = $in_list['1'];
                $i_sql = "insert into org_relation (user_id,superior_id,level) value ($u_id,$s_id,$level)";
                $this->execute($i_sql,array(),$this->writedb);
            }

            //删除已离职人员的上下级关系
            if(!empty($job_status_del)) { // by coldarmy 20120704 直接删除
                foreach($job_status_del as $v) {
                    $d_sql = "delete from org_relation where user_id = {$v}";
                    $this->execute($d_sql,array(),$this->writedb);
                    $d_sql = "delete from org_relation where superior_id = {$v}";
                    $this->execute($d_sql,array(),$this->writedb);
                }
            }
        }*/
    }

    //获得用户的层级关系
    public function get_relation_level($v_id,$user_id,$user_relation,$level = 1) {
        $pid = $user_relation[$user_id];
        if(empty($pid)) {
            $this->user_lelation_level[$v_id.'_'.$user_id] = $level;
            return true;
        }

        $level = $level+1;
        $level = $this->get_relation_level($v_id,$pid,$user_relation,$level);
        $this->user_lelation_level[$v_id.'_'.$user_id] = $level;
        return true;
    }

    //获得金蝶部门与线下部门id的对应关系
    public function get_kd_department_ids() {
        //得到金蝶部门对线下id的关系
        $kd_department_ids = array();
        $s_sql = "select * from department";
        $oa_department = $this->get_db_rows_assoc($s_sql, $this->readdb);
        foreach((array)$oa_department as $v) {
            $kd_department_ids[$v['kd_department_id']] = $v['department_id'];
        }
        return $kd_department_ids;
    }

    //导出没有上级的用户
    public function import_superior_null_info() {
        $s_sql = "select * from user_info left join org_relation on user_info.user_id=org_relation.user_id where org_relation.superior_id=0 and job_status<>'离职' and dimission_date='0000-00-00 00:00:00'";
        $rs = $this->get_db_rows($s_sql, $this->readdb);

        if(!empty($rs)) {
            $fp = fopen('/home/eddietian/report.txt','a+');
            foreach($rs as $v) {
                fwrite($fp,$v['code'].','.$v['name'].','.substr($v['enter_date'],0,10)."\n");
            }
            fclose($fp);
        }
        return true;
    }

    //导出金蝶里面坏的部门信息
    public function import_bad_department_info() {
        $s_sql = "select ID,Name,CompanyID,FullName,StatusID from ORG_Unit,ORG_Department where ID = UnitID order by StatusID asc";
        $result = mssql_query($s_sql);
        $data = array();
        $kd_department_ids = array();//将金蝶的id放到ids数组里
        $kd_company_ids = array();//金蝶的公司名id,供同步公司名使用
        while( $row = mssql_fetch_assoc($result) ) {
            $rs = array();
            $rs['kd_name'] = $this->set_utf8($row['Name']);
            $rs['kd_FullName'] = $this->set_utf8($row['FullName']);
            $rs['kd_id'] = mssql_guid_string($row['ID']);
            $rs['company_id'] = mssql_guid_string($row['CompanyID']);
            $rs['statusid'] = mssql_guid_string($row['StatusID']);
            $kd_company_ids[] = mssql_guid_string($row['CompanyID']);
            $kd_department_ids[] = $rs['kd_id'];
            $data[$rs['kd_id']] = $rs;
        }

        //同步部门表的公司名
        if(!empty($kd_company_ids)) {
            $kd_company_ids = array_unique($kd_company_ids);
            $in_list = implode("','",$kd_company_ids);
            $in_list = "'".$in_list."'";
            $s_sql = "select ID,Name from ORG_Unit where ID in($in_list)";
            $result = mssql_query($s_sql);
            $rs = array();
            while( $row = mssql_fetch_assoc($result) ) {
                $row['ID'] = mssql_guid_string($row['ID']);
                $row['Name'] = $this->set_utf8($row['Name']);
                $rs[$row['ID']] = $row['Name'];
            }
        }

       foreach($data as $key=>$v) {
              $c_id = $v['company_id'];
              $data[$key]['company_name'] = $rs[$c_id];
       }

       $fp = fopen('/home/eddietian/report_bad.txt','a+');
       foreach($data as $v) {
           fwrite($fp,$v['kd_id'].','.$v['company_name'].','.$v['kd_name'].','.$v['kd_FullName'].','.$v['statusid']."\n");
       }
       fclose($fp);
    }

    public function set_utf8($str) {
        $origin = mb_detect_encoding($str,array('CP936','UTF-8','ASCII','GBK','GB2312'));
        return mb_convert_encoding($str,'UTF-8',$origin);
    }

    /**
     * 需要排查的部门ids
     * @return multitype:unknown
     */
    public function get_department_bad_ids() {
        $department_bad_ids = array();
        if(file_exists($this->department_bad_file)) {
            $fp = fopen($this->department_bad_file, 'r');
            while (!feof($fp)) {
                $tmp = array();
                $val = fgetcsv($fp);
                if(empty($val)) {
                    continue;
                }
                $department_bad_ids[$val[0]] = $val[0];
            }
            fclose($fp);
        }
        if(empty($department_bad_ids)) {
            return array();
        }

        $in_list = implode("','",$department_bad_ids);
        $in_list = "'".$in_list."'";
        $s_sql = "select UnitID,Name from HR_v_Report_EmployeeAllDetailInfo where UnitID in ($in_list)";
        $result = mssql_query($s_sql);

        while( $row = mssql_fetch_assoc($result) ) {
            $name = $this->set_utf8($row['Name']);
            if(!empty($name)) {
                $unitid = mssql_guid_string($row['UnitID']);
                unset($department_bad_ids[$unitid]);
            }
        }
        return $department_bad_ids;
    }

    /**
     * 遍历等级关系
     */
    public function map_relation($base_code, $user_code, $user_s_code, $level = 1) {
        // 自己是自己的上司
        if ($user_code == $user_s_code) {
            return false;
        }
        // 没有上级
        if ($user_s_code == '') {
            return false;
        }
        //所有用户信息
        $users = $this->user_ids;

        $base_id = $users[$base_code]['user_id'];
        $user_s_id = $users[$user_s_code]['user_id'];
        if($users[$user_s_code] == NULL){
            //TODO 说明上级已经离职了，记录日志
            self::$dismission[] = $user_code.",".$user_s_code;
            return false;
        }
        // 有上级，递归查找
        if ($user_s_code != '') {
            $sql = "insert into org_relation(user_id,superior_id,level) values({$base_id},{$user_s_id},{$level})";
            if ($this->execute($sql,array(),$this->writedb)) {
                echo "insert user_id {$base_id} --> user_s_id -->{$user_s_id} --> level --> {$level} ok \n";
            }
            ++ $level;
            // 最多遍历十层，防止死循环
            if ($level > 10) {
                echo "死循环了...";
                // TODO邮件通知
                exit ();
            }
            $user_s_s_code = $users[$user_s_code]['superior_code'];
            @$this->map_relation ( $base_code, $user_s_code, $user_s_s_code, $level );
        }
    }

    /**
     * 所有用户id信息
     */
    private function  get_all_ids(){
        //都是在职的，dimission作为判断标准
        $sql = "SELECT u.user_id,u.`code`,u.superior_code FROM user_info u WHERE u.dimission_date = '0000-00-00 00:00:00'";
        $rows = $this->get_db_rows($sql, $this->readdb);
        $date = array();
        foreach ($rows as $row){
            $date[$row['code']] = array('user_id'=>$row['user_id'],'superior_code'=>$row['superior_code']);
        }
        $this->user_ids = $date;
        //return $date;
    }

    /**
     * 清空数据库
     * @param unknown_type $db_name
     */
    private function clear_db($db_name){
        $sql = "delete from $db_name";
        echo $sql;
        return $this->execute($sql,array(),$this->writedb);
    }

    /**
     * 重置自增id
     * @param unknown_type $db_name
     */
    private function alter_db($db_name){
        $sql = "alter table $db_name AUTO_INCREMENT=1";
        return $this->execute($sql,array(),$this->writedb);
    }

    public function db_connect() {
        $dbhost = "192.168.1.60";
        $dbusname = "sa";
        $dbpasswd = "sa";
        $dbname = "AIS20100415101750";
        $conn = mssql_connect(
            $dbhost,
            $dbusname,
            $dbpasswd
        );
        mssql_select_db($dbname,$conn);
    }
}
